<?php
namespace api\controllers;

use common\models\Active;
use common\models\Order;
use common\models\Shop;
use common\models\UserCollection;
use common\service\ActiveService;
use common\service\ConstantService;
use common\models\User;
use common\service\WechatService;
use common\service\GlobalUrlService;
class UserController extends BaseController
{
    /**
     * 获取用户Token
     */
    public function actionAutoLogin(){
        if($this->isGet()){
            $code = $this->get('code');
            $appid = \Yii::$app->params['wechat']['appid'];
            $secret = \Yii::$app->params['wechat']['secret'];
            $request = WechatService::getWechatOpenid($code,$appid,$secret);
            if(!$request){
                return $this->renderJson([],'获取openid失败!',ConstantService::$response_fail);
            }
            $request = json_decode($request,true);

            if(isset($request['errcode'])){
                return $this->renderJson([],'code无效',ConstantService::$response_fail);
            }
            $openid = $request['openid'];
            $user = User::find()->where(['openid'=>$openid])->asArray()->one();

            if(empty($user)){
                //用户不存在入库
                $user_model = new User();
                $data['openid'] = $openid;
                $data['create_time'] = time();
                $user_model->setAttributes($data);
                if(!($user_model->save())){
                    return $this->renderJson([],'用户信息存储失败',ConstantService::$response_fail);
                }
            }
            $token = base64_encode(base64_encode($openid).'-'.$this->salt);
            //最终都返回Token
            if(empty($user['nickname'])){
                return $this->renderJson($token,'该用户未授权',ConstantService::$response_fail_auth);
            }
            return $this->renderJson($token,'操作成功',ConstantService::$response_success);
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);
    }

    /**
     * 更新用户信息
     */
    public function actionSaveUserInfo(){
        if($this->isPost()){
            $data = $this->post();
            $user_id = $this->user['id'];
            //这里需要把微信头像存到我们这边
            $user_model = User::findOne(['id'=>$user_id]);
            $user_model['avatarurl'] = WechatService::getUserHeader($data['url']);
            $user_model['nickname'] = base64_encode($data['nickname']);
            if($user_model && $user_model->save()){
                return $this->renderJson([],'保存成功',ConstantService::$response_success);
            }
            return $this->renderJson([],'保存失败',ConstantService::$response_fail);
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);
    }

    /**
     * 获取用户信息
     */
    public function actionGetUser(){
        if($this->isGet()){
            $user_id = $this->user['id'];
            $user = User::find()->where(['id'=>$user_id])->asArray()->one();
            $user['avatarurl'] = GlobalUrlService::buildCdnUrl($user['avatarurl']);
            $user['nickname'] = !empty($user['nickname']) ?base64_decode($user['nickname']) :'';
            $dfkorder = Order::find()->select('count(*) as count')->where(['order_status'=>0,'user_id'=>$user_id,'is_delete'=>0])->asArray()->one();
            $user['dfk'] = $dfkorder['count'];

            $dfhorder = Order::find()->select('count(*) as count')->where(['order_status'=>1,'user_id'=>$user_id,'is_delete'=>0])->asArray()->one();
            $user['dfh'] = $dfhorder['count'];

            $dshorder = Order::find()->select('count(*) as count')->where(['order_status'=>3,'user_id'=>$user_id,'is_delete'=>0])->asArray()->one();
            $user['dsh'] = $dshorder['count'];
            return $this->renderJson($user,'获取成功',ConstantService::$response_success);
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);
    }

    /**
     * 获取用户收藏
     */
    public function actionGetCollection(){
        if($this->isGet()){
            $user_id = $this->user['id'];
            $page = intval($this->get('page'));
            $status = $this->get('status'); // 0 浏览记录  1 用户收藏
            $type = $this->get('type'); // 0 活动id  1 店铺id
            if($status != 0 &&  $status != 1){
                return $this->renderJson([],'参数错误',ConstantService::$response_fail);
            }
            $page = ( $page > 0 )? $page : 1;
            $offset = ($page - 1) * $this->page_size;
            $collections = UserCollection::find()
                ->where(['user_id'=>$user_id,'status'=>$status,'type'=>$type])
                ->orderBy(['update_time' =>SORT_DESC ])
                ->offset( $offset )
                ->limit( $this->page_size )
                ->asArray()
                ->all();

            if(!empty($collections)){
                $activeids = array_column($collections,'list_id');
                $actives = Active::find()
                    ->select(['id','goods_id','active_name','type','goods_img','max_price','min_price'])
                    ->where(['id'=>$activeids])
                    ->asArray()
                    ->all();
                $new_actives = [];
                foreach ($actives as &$active){
                    $active['goods_img'] = GlobalUrlService::buildCdnUrl($active['goods_img']);
                    $active['type'] = ConstantService::$active_type[$active['type']];
                    $lenth = mb_strlen($active['active_name']);
                    if($lenth > 26){
                        $active['active_name'] = mb_substr($active['active_name'],0,26).'...';
                    }
                    $new_actives[$active['id']] = $active;
                }

                foreach ($collections as &$collection){
                    $collection['data'] = '';
                    $collection['create_time'] = date('Y-m-d H:i:s');
                    //活动
                    if(isset($new_actives[$collection['list_id']]) && !empty($new_actives[$collection['list_id']])){
                        $collection['data'] = $new_actives[$collection['list_id']];
                    }
                }
            }
            return  $this->renderJson($collections,'获取成功',ConstantService::$response_success);
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);

    }

    /**
     * 获取用户收货地址 第一个为默认收货地址
     */
    public function actionGetAddress(){
        if($this->isGet()){
            $user_id = $this->user['id'];
            $lists = Address::find()
                ->where(['id'=>$user_id])
                ->orderBy(['status' => SORT_DESC])
                ->asArray()
                ->all();
            return $this->renderJson($lists,'',ConstantService::$response_success);
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);
    }

    /**
     * 添加收藏
     */
    public function actionAddCollection(){
        if($this->isGet()){
            $user_id = $this->user['id'];
            $active_id = $this->get('id');
            $type = $this->get('type'); // 0 活动id  1 店铺id
            if(empty($active_id)){
                return $this->renderJson([],'参数错误',ConstantService::$response_fail);
            }
            $data['user_id'] = $user_id;
            $data['list_id'] = $active_id;
            $data['type'] = $type;
            $data['status'] = 1;
            $data['create_time'] = time();
            $data['update_time'] = time();
            $collection_query = new UserCollection();
            $collection_query->setAttributes($data);
            if($collection_query->save()){
                return $this->renderJson([],'收藏成功',ConstantService::$response_success);
            }
            return $this->renderJson([],'收藏失败',ConstantService::$response_fail);
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);
    }

    /**
     * 取消收藏
     */
    public function actionDelCollection(){
        if($this->isGet()){
            $active_id = $this->get('id');
            $user_id = $this->user['id'];
            if(empty($active_id)){
                return $this->renderJson([],'参数错误',ConstantService::$response_fail);
            }
            $conditions = ['user_id' => $user_id,'list_id' => $active_id,'status'=>1];
            $row = UserCollection::findOne($conditions);

            if($row->delete()){
                return $this->renderJson([],'取消成功',ConstantService::$response_success);
            }
            return $this->renderJson([],'取消失败',ConstantService::$response_fail);

        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);

    }

    /**
     * 获取用户收藏的店铺
     */
    public function actionGetShopCollection(){
        if($this->isGet()){
            $user_id = $this->user['id'];
            $page = intval($this->get('page'));
            $status = 1; // 0 浏览记录  1 用户收藏
            $type = 1; // 0 活动id  1 店铺id
            if($status != 0 &&  $status != 1){
                return $this->renderJson([],'参数错误',ConstantService::$response_fail);
            }
            $page = ( $page > 0 )? $page : 1;
            $offset = ($page - 1) * $this->page_size;
            $collections = UserCollection::find()
                ->where(['user_id'=>$user_id,'status'=>$status,'type'=>$type])
                ->orderBy(['update_time' =>SORT_DESC ])
                ->offset( $offset )
                ->limit( $this->page_size )
                ->asArray()
                ->all();

            if(!empty($collections)){
                $ids = array_column($collections,'list_id');
                $count_shop = UserCollection::find()
                    ->select(['list_id,count(id) as count'])
                    ->where(['list_id'=>$ids,'status'=>$status,'type'=>$type])
                    ->groupBy(['list_id'])
                    ->asArray()
                    ->all();
                $new_count_shop = [];
                foreach ($count_shop as &$val){
                    $new_count_shop[$val['list_id']] = $val['count'];
                }
                unset($val);
                $shop = Shop::find()
                    ->select(['id','shop_name','shop_logo'])
                    ->where(['id'=>$ids])
                    ->asArray()
                    ->all();
                $new_shop = [];

                foreach ($shop as &$val){
                    $val['shop_logo'] = GlobalUrlService::buildCdnUrl($val['shop_logo']);
                    $new_shop[$val['id']] = $val;
                }

                foreach ($collections as &$collection){
                    $collection['create_time'] = date('Y-m-d H:i:s');
                    $collection['count'] = '';
                    $collection['shop'] = [];
                    if(isset($new_count_shop[$collection['list_id']]) && !empty($new_count_shop[$collection['list_id']])){
                        $collection['count'] = $new_count_shop[$collection['list_id']];
                    }
                    if(isset($new_shop[$collection['list_id']]) && !empty($new_shop[$collection['list_id']])){
                        $collection['shop'] = $new_shop[$collection['list_id']];
                    }
                }
            }
            return  $this->renderJson($collections,'获取成功',ConstantService::$response_success);
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);

    }



}